package top.codecrab.eblog.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.codecrab.eblog.common.response.R;
import top.codecrab.eblog.entity.Category;
import top.codecrab.eblog.entity.Post;
import top.codecrab.eblog.search.mq.MqTypes;
import top.codecrab.eblog.shiro.AccountProfile;
import top.codecrab.eblog.utils.CommonUtils;
import top.codecrab.eblog.utils.ShiroUtil;
import top.codecrab.eblog.utils.UploadUtil;
import top.codecrab.eblog.utils.ValidationUtil;
import top.codecrab.eblog.vo.CommentVo;
import top.codecrab.eblog.vo.PostVo;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 文章表 前端控制器
 * </p>
 *
 * @author codecrab
 * @since 2021-08-21
 */
@Controller
public class PostController extends BaseController {

    @GetMapping("/postCaptcha.jpg")
    public void postCaptcha(HttpServletResponse response) throws IOException {
        //验证码文字
        String text = producer.createText();
        //放入redis
        redisUtil.set(POST_CAPTCHA_KEY + CommonUtils.getRemoteHost(request), text, 300, TimeUnit.SECONDS);
        //验证码图片
        BufferedImage image = producer.createImage(text);
        //设置页面不缓存
        response.setHeader("Cache-Control", "no-store, no-cache");
        //设置写入文件的类型
        response.setContentType("image/jpeg");
        //写入到页面
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    @GetMapping("/post/{id:\\d*}")
    public String detail(@PathVariable("id") Long id) {
        //查询文章
        PostVo postVo = postService.detail(id);
        Assert.notNull(postVo, "文章不存在或已被删除");
        //查询评论 1、分页 2、文章id 3、用户id 4、排序
        IPage<CommentVo> commentList = commentService.paging(getPage(), id, null, "created");

        //增加阅读量到缓存
        postService.cacheViewCount(postVo, request);

        //页面markdown显示有问题，在前面换一行就没事了
        postVo.setContent("\n" + postVo.getContent());
        request.setAttribute("post", postVo);
        request.setAttribute("pageData", commentList);
        request.setAttribute("currentCategoryId", postVo.getCategoryId());
        return "/post/detail";
    }

    @GetMapping("/post/edit")
    public String postEdit() {
        String id = request.getParameter("id");
        if (!StringUtils.isBlank(id)) {
            //发布，设置回显
            Post post = postService.getOne(new QueryWrapper<Post>().eq("id", id));
            Assert.notNull(post, "帖子不存在或已删除");
            Long profileId = ShiroUtil.getProfileId();
            if (profileId == null || profileId != 1) {
                Assert.isTrue(post.getUserId().equals(profileId), "您没有权限修改不属于您的文章");
            }
            request.setAttribute("post", post);
            request.setAttribute("type", "发布");
        }
        //编辑
        request.setAttribute("categories", categoryService.list(new QueryWrapper<Category>().eq("status", 0)));
        request.setAttribute("type", "编辑");
        return "/post/edit";
    }

    /**
     * 新增或编辑文章
     */
    @ResponseBody
    @PostMapping("/post/submit")
    public R postSubmit(Post post, String verCode) {
        String captcha = (String) redisUtil.get(POST_CAPTCHA_KEY + CommonUtils.getRemoteHost(request));
        redisUtil.del(POST_CAPTCHA_KEY + CommonUtils.getRemoteHost(request));
        if (!StringUtils.equals(verCode, captcha)) {
            return R.fail("图形验证码不匹配或已过期，请刷新后重试");
        }

        ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(post);
        //校检表单信息
        if (validResult.hasErrors()) {
            return R.fail(validResult.getErrors());
        }

        return postService.saveOrUpdatePost(post);
    }

    /**
     * 删除文章
     */
    @ResponseBody
    @PostMapping("/post/delete")
    public R postDelete(Long id) {
        postService.delete(id);
        return R.ok().action("/user/index");
    }

    @GetMapping("/post/delete")
    public String delete(Long id) {
        postService.delete(id);
        return "/user/index";
    }

    /**
     * 上传博客图片
     */
    @ResponseBody
    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
        try {
            R res = UploadUtil.upload(UploadUtil.TYPE_POST, file);

            if (res.getStatus() != 0) {
                return MapUtil.builder("message", (Object) res.getMsg())
                    .put("success", 0).put("status", -1).build();
            }

            return MapUtil.builder("message", (Object) "上传成功")
                .put("success", 1).put("status", 0)
                .put("url", res.getData().toString()).build();

        } catch (IOException e) {
            return MapUtil.builder("message", (Object) "上传成功")
                .put("success", 0).put("status", -1).build();
        }
    }
}
